const Router = require('koa-router');
const router = new Router();
const {db, QueryTypes, Op} = require("../../models/db");
// 审核
const {detectStock, detectHasReceipt, billCanEdit,updateInventory, hxYusf} = require("./base");
const tool = require("../../tools/tool");
// 作废
router.post('/bill/toWasted', async ctx => {
    let transType = ctx.request.body.transType
    let canWasteAuto = false // 是否可作废自动生成票据
    if(ctx.request.body.canWasteAuto) {
        canWasteAuto = true
    }

    try {
        let id = ctx.request.body.ids[0];
        let uid = ctx.user.id
        let tenantId = ctx.user.tenantId
        if(transType === 190001) {
            let cards = await db.models['card'].findOne({
                where: {
                    tenantId,
                    id
                }
            })
            if(!canWasteAuto) {
                if(cards.isAuto === 1) {
                    return ctx.err('不能退审自动生成票据')
                }
            }
            await billCanEdit(cards.billDate, tenantId);

            if(cards.billState !== 'accounted') {
                return ctx.err('不是已审核数据')
            }
            cards.billState = 'draft'
            cards.updatedBy = uid
            cards.updatedAt = tool.getTime()
            cards.wastedBy = uid
            cards.wastedAt = tool.getTime()
            await cards.save()
        }
        else {
            let invoice = await db.models['invoice'].findOne({
                where: {
                    tenantId,
                    id
                }
            })
            if(!invoice)  return ctx.err('未找到票据')
            if(!canWasteAuto) {
                if(invoice.isAuto === 1) {
                    return ctx.err('不能退审自动生成的票据')
                }
            }
            let transType = tool.xe.toNumber(invoice.transType)
            if (!invoice) return ctx.err('没有找到票据')
            let billType = invoice.billType
            if (invoice.billState !== 'accounted') return ctx.err('未审核票据')
            if (tool.xe.toNumber(invoice.isInit) === 1) return ctx.err('不能退审期初数据')
            if (invoice.billType === 'SALE' || invoice.billType === 'PUR') {
                // 是否有收付款记录
                await detectHasReceipt(ctx.user.tenantId, id);
            }
            await billCanEdit(invoice.billDate, tenantId);
            if (['SALE', 'PUR', 'OO', 'OI'].indexOf(billType) !== -1) {
                // 检测库存
                // await detectStock(id, 1)
            }
            if (transType === 153406 || transType === 153407) {
                let sqls = ` select top 1 b.billNo from invoice_dikou a inner join invoice b on a.iid=b.id and a.relId=${id} `;
                let used = await db.query(sqls, { type: QueryTypes.SELECT, plain: true })
                if (used) {
                    return ctx.err(`已在票据 ${used.billNo} 中抵扣, 不能退审`)
                }
            }
            invoice.billState = 'draft'
            invoice.wastedAt = tool.getTime()
            invoice.wastedBy = ctx.user.id
            invoice.updatedAt = tool.getTime()
            // 退审票据主表
            invoice.accountedAt = null;
            invoice.accountedBy = null
            await db.transaction(async () => {
                await invoice.save()
                // 更新库存
                if ([150601, 150602, 150603, 150501, 150502, 150706, 150806].indexOf(transType) !== -1) {
                    await updateInventory(tenantId, invoice.id, 'cal', 1)
                    await hxYusf(invoice, 'waste')
                }

                await db.models['card'].update({
                    billState: 'del'
                }, {
                    where: {
                        tenantId: tenantId,
                        byIid: invoice.id
                    }
                })
            })
            tool.saveLogInvoice(tenantId, uid, invoice.id, "退审", invoice,);
            return ctx.suc('已退审')
        }
        return ctx.suc('已退审')
    }
    catch (e) {
        return ctx.err(e)
    }
})
// 退审有 预收，预付票据的 采购，销售单  删除自动生成的核销单
const delHxDikou = async (invoice) => {
    let transType = invoice.transType
    let tenantId = invoice.tenantId
    if(transType === 150501 || transType === 150601) {

    }
}

module.exports = router;